package com.youxin.chat.pay.service.channel.impl.ainong.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import com.youxin.chat.pay.utils.ParamStringUtils;
import com.youxin.chat.pay.utils.RSAUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.PrivateKey;
import java.security.PublicKey;

public class AinongSignUtil {

    private static final Logger logger = LoggerFactory.getLogger(AinongSignUtil.class);

    public static String buildSign(JSONObject jsonObject, String privateKeyStr) {
        PrivateKey privateKey = RSAUtils.loadPrivateKey(privateKeyStr);
        String str =  JSONObject.toJSONString(jsonObject, SerializerFeature.MapSortField, SerializerFeature.WriteNullStringAsEmpty);
        logger.info("爱农加签字符串,data={}", str);
        try {
            byte[] signBytes = RSAUtils.doSignature256(str, privateKey, "utf-8");
            return Base64.encodeBase64String(signBytes);
        } catch (Exception e) {
            logger.error("爱农加签失败，error=", e);
            return null;
        }
    }

    public static boolean verifySign(String str,String publicKeyStr) {
        JSONObject respJsonObj = JSONObject.parseObject(str);
        String signature = (String)respJsonObj.remove("signature");

        String signMsg = JSONObject.toJSONString(respJsonObj, SerializerFeature.MapSortField, SerializerFeature.WriteNullStringAsEmpty);

        PublicKey publicKey = RSAUtils.loadPubKeyByStr(publicKeyStr);
        try {
            return RSAUtils.verfy(Base64.decodeBase64(signature), signMsg.getBytes(), "SHA256WithRSA", publicKey);
        } catch (Exception e) {
            logger.error("爱农验签失败，error=", e);
            return false;
        }
    }

    public static boolean verifyNotifySign(String str,String publicKeyStr) {
        JSONObject respJsonObj = JSONObject.parseObject(str);
        String signature = (String)respJsonObj.get("signature");

        String signMsg = ParamStringUtils.toSignStrIncludEmpty(respJsonObj, "signature");
        logger.info("爱农验签 字符串,data={}", signMsg);

        PublicKey publicKey = RSAUtils.loadPubKeyByStr(publicKeyStr);
        try {
            return RSAUtils.verfy(Base64.decodeBase64(signature), signMsg.getBytes(), "SHA256WithRSA", publicKey);
        } catch (Exception e) {
            logger.error("爱农验签失败，error=", e);
            return false;
        }
    }
}
